<template>
  <div>
    <a-card :bordered="false">
      <div class="table-page-search-wrapper">
        <zh-form ref="queryParam" :model="queryParam" style="padding-top: 10px;">
          <a-row :gutter="8">
            <zh-input prop="fullName" label="操作用户" allowClear type="search" :searchUrl="getUserListInfo" searchField="fullName"
                      :searchFormatField="['userTypeName','fullName','idcard']" :defaultFields="{label:'idcard', value:'fullName'}"
                      :showSearchField="['fullName']" v-model="queryParam.fullName" @cell-click="userSearchClick($event)"></zh-input>
            <zh-input prop="title" label="业务名称" allowClear v-model="queryParam.title"></zh-input>
            <template v-if="advanced">
              <zh-input prop="code"  placeholder="请选择" type="select" allowClear :options="dictData.code" label="成功标志" v-model="queryParam.code"></zh-input>
              <zh-input prop="ym"  type="month"  label="请求年月" v-model="queryParam.ym"></zh-input>
              <zh-input prop="begTimeStart" :disabledDate="disabledStartDate" :allowClear="true" :showTime="true" type="date"
                        label="请求时间开始" format="YYYY-MM-DD HH:mm:ss" v-model="queryParam.begTimeStart"
                        placeholder="请输入开始时间"
                        @openChange="handleStartOpenChange">
              </zh-input>
              <zh-input prop="begTimeEnd" :disabledDate="disabledEndDate" :allowClear="true" :showTime="true" type="date"
                        label="请求时间结束" format="YYYY-MM-DD HH:mm:ss" v-model="queryParam.begTimeEnd"
                        placeholder="请输入结束时间"
                        :open="endOpen"
                        @openChange="handleEndOpenChange">
              </zh-input>
              <zh-input prop="reqParams" label="请求参数" placeholder="支持模糊查询" allowClear v-model="queryParam.reqParams"></zh-input>
              <zh-input prop="routerId"  type="tree" :showSearch="true" label="所属路由"
                        v-model="queryParam.routerId"
                        :value="routerSelectTreeValue"
                        :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                        placeholder="单选"
                        treeNodeFilterProp="title"
                        allowClear
                        :treeDefaultExpandAll="true"
                        :tree-data="routerSelectTreeData"
                        @change="onChangeRouterSelectTree"
                        @search="onSearchRouterSelectTree"
                        @select="onSelectRouterSelectTree"
              >
              </zh-input>
              <zh-input v-if="funcSelectType==='tree'" prop="funcId"  type="tree" :showSearch="true" label="所属功能"
                        v-model="queryParam.funcId"
                        :value="funcSelectTreeValue"
                        :dropdownStyle="{ maxHeight: '400px', overflow: 'auto' }"
                        placeholder="单选"
                        treeNodeFilterProp="title"
                        allowClear
                        :treeDefaultExpandAll="true"
                        :tree-data="funcSelectTreeData"
                        @change="onChangeFuncSelectTree"
              >
              </zh-input>
              <zh-input v-if="funcSelectType==='select'" prop="funcId"  placeholder="请选择" type="select"
                        allowClear :options="funcSelectData" label="所属功能"
                        :defaultFields="{label: 'funcTitle',value: 'funcId',}"
                        v-model="queryParam.funcId">
              </zh-input>
              <zh-input prop="reqApi" label="请求API"  placeholder="精确查找" allowClear v-model="queryParam.reqApi"></zh-input>
            </template>
            <a-col :md="!advanced && 8 || 24" :sm="24">
              <span class="table-page-search-submitButtons" :style="advanced && { float: 'right', overflow: 'hidden' } || {} ">
                <a-checkbox @change="onHistroyChange">查询历史</a-checkbox>
                <a-button type="primary" @click="() =>{this.findListBtn()}">查询</a-button>
                <a-button style="margin-left: 8px" @click="() => {this.clearAll()}">重置</a-button>
                <a @click="toggleAdvanced" style="margin-left: 8px">
                  {{ advanced ? '收起' : '展开' }}
                  <a-icon :type="advanced ? 'up' : 'down'"/>
                </a>
              </span>
            </a-col>
          </a-row>
        </zh-form>
      </div>
      <vxe-grid
          class="vxe-table-antd"
          resizable
          show-overflow
          ref="listTable"
          stripe
          border
          highlight-hover-row
          highlight-current-row
          highlight-hover-column
          highlight-current-column
          highlight-cell
          height="400"
          size="small"
          :columns="tableColumn"
          row-id="reqLogId"
          :data="tableData"
          :loading="loading"
          :start-index="(tablePage.currentPage - 1) * tablePage.pageSize"
          :pager-config="tablePage"
          @page-change="handlePageChange"
      >
      </vxe-grid>
      <a-modal
          title="请求参数详情"
          centered
          style="top: 10px;"
          width="80%"
          destroyOnClose
          v-model="visible"
          :footer="null"
      >
        <json-viewer :value="reqParams"></json-viewer>
      </a-modal>
    </a-card>
  </div>
</template>

<script>
import { getRouterTreeList, getRouterFunctionList,getFunctionTreeList } from "@/services/system/api"
import { getOplogApiList,getUserList } from "@/services/system/whdngxlApi"
import modal from 'ant-design-vue/es/modal'
import moment from 'moment'
const flagMap = {
  '-1': {
    status: 'error',
    text: '失败'
  },
  '0': {
    status: 'success',
    text: '成功'
  }
}
export default {
  name: 'UserReqLog',
  components: {
  },
  data () {
    return {
      getUserListInfo:getUserList,
      description: '用户请求日志',
      dictData: {
        code:[{dictKey:'-1',dictValue:'失败'},{dictKey:'0',dictValue:'成功'}]
      },
      dictUser: [],
      endOpen: false,
      visible: false,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 17 }
      },
      form: null,
      // 高级搜索 展开/关闭
      advanced: true,
      // 查询参数
      queryParam: {
        userId:'',
        fullName:'',
      },
      // 表头
      loading: false,
      tablePage: {
        total: 0,
        currentPage: 1,
        pageNum: 1,
        pageSize: 200
      },
      tableColumn: [
        { type: 'seq', width: 80, fixed: 'left', align: 'center', title: '序号' },
        { field: 'reqLogId', title: '请求日志Id', visible: false, fixed: 'left', align: 'center', width: 150 },
        { field: 'title', title: '业务名称', align: 'center', fixed: 'left', width: 200 },
        { field: 'userId', title: '用户Id', visible: false, align: 'center', width: 150 },
        { field: 'userName', title: '用户名', align: 'center', width: 150 },
        { field: 'fullName', title: '姓名', align: 'center', width: 200 },
        { field: 'ym', title: '所属年月', align: 'center', width: 80 },
        { field: 'code', title: '成功标识', align: 'center', width: 80, slots: { default: ({ row }) => { return [this.formatflag(row.code)] } } },
        { field: 'message', title: '描述', align: 'center', width: 300 },
        { field: 'reqApi', title: '请求API', align: 'center', width: 250 },
        { field: 'begTime', title: '请求时间', align: 'center', width: 200 },
        { field: 'endTime', title: '返回时间', align: 'center', width: 200 },
        { field: 'countTime', title: '耗时（秒）', align: 'center', width: 80 },
        { field: 'routerId', title: '路由id', align: 'center', width: 150 },
        { field: 'funcId', title: '功能Id', align: 'center', width: 150 },
        { field: 'ip', title: '请求客户端IP', align: 'center', width: 150 },
        { field: 'serverIp', title: '服务器IP', align: 'center', width: 250 },
        { field: 'serverPort', title: '服务器端口', align: 'center', width: 200 },
        { field: 'servletContext', title: '服务名', align: 'center', width: 200 },
        { field: 'reqParams', title: '请求参数', align: 'center', width: 350 },
        { field: 'action', title: '详情', align: 'center', fixed: 'right', width: 100, slots: { default: ({ row }) => { return [ <a-button type="link" onClick={ () => this.openParamInfo(row.reqParams) } >参数详情</a-button> ] } } }
      ],
      tableData: [],
      selectData: {},
      routerSelectTreeValue: undefined,
      funcSelectTreeValue: undefined,
      routerSelectTreeData: [],
      funcSelectTreeData: [],
      funcSelectData:[],
      funcSelectType:'tree',
      isHistoryChecked: false,
      reqParams: null
    }
  },
  created () {
    // 数据初始化
    const queryParams = {}
    setTimeout(() => {
      this.$http.post(getRouterTreeList,queryParams).then((res) => {
        this.routerSelectTreeData = res.result.routerList
      }).catch(() => {
      })
    }, 20)
    this.getFunctionTreeList()
  },
  methods: {
    moment,
    userSearchClick(row){
      this.queryParam.userId=row.userId
    },
    onChangeRouterSelectTree (value) {
      console.log(value)
      this.routerSelectTreeValue = value
      this.getFunctionTreeList()
    },
    onSearchRouterSelectTree () {
      console.log(...arguments)
    },
    onSelectRouterSelectTree () {
      console.log(...arguments)
    },
    onChangeFuncSelectTree (value) {
      console.log(value)
      this.funcSelectTreeValue = value
    },
    getFunctionTreeList () {
      let that = this
      const params = {}
      if (this.routerSelectTreeValue) {
        params.routerId = this.routerSelectTreeValue
        setTimeout(() => {
          this.$http.post(getRouterFunctionList,params).then((res) => {
            this.funcSelectData = res.result
            this.funcSelectType='select';
          }).catch(() => {
          })
        }, 20)
      } else {
        this.$http.post(getFunctionTreeList,params).then((res) => {
          this.funcSelectType='tree';
          this.funcSelectTreeData = res.result.functionList
        }).catch(() => {
        })
      }
    },
    filterOption (input, option) {
      return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    formatflag (cellValue) {
      let value = cellValue
      if (value) {
        if (value !== '0') {
          value = '-1'
        }
        const text = flagMap[value].text
        const status = flagMap[value].status
        if (text) {
          return <a-badge status={status} text={text}/>
        } else {
          return cellValue
        }
      }
    },
    disabledStartDate (loginTimeBeg) {
      const loginTimeEnd = this.queryParam.loginTimeEnd
      if (!loginTimeBeg || !loginTimeEnd) {
        return false
      }
      return loginTimeBeg.valueOf() > loginTimeEnd.valueOf()
    },
    disabledEndDate (loginTimeEnd) {
      const loginTimeBeg = this.queryParam.loginTimeBeg
      if (!loginTimeEnd || !loginTimeBeg) {
        return false
      }
      return loginTimeBeg.valueOf() >= loginTimeEnd.valueOf()
    },
    handleStartOpenChange (open) {
      if (!open) {
        this.endOpen = true
      }
    },
    handleEndOpenChange (open) {
      this.endOpen = open
    },
    toggleAdvanced () {
      this.advanced = !this.advanced
    },
    handlePageChange ({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage
      this.tablePage.pageNum = currentPage
      this.tablePage.pageSize = pageSize
      this.findList()
    },
    findListBtn () {
      this.tablePage.currentPage = 1
      this.tablePage.pageNum = 1
      this.findList()
    },
    // 列表查询
    findList () {
      this.loading = true
      const params = Object.assign(this.queryParam, this.tablePage)
      if(this.queryParam.begTimeStart){
        params.begTimeStart =moment(this.queryParam.begTimeStart).format('YYYY-MM-DD HH:mm:ss')
      }
      if(this.queryParam.begTimeEnd){
        params.begTimeEnd =moment(this.queryParam.begTimeEnd).format('YYYY-MM-DD HH:mm:ss')
      }
      params.history = this.isHistoryChecked
      setTimeout(() => {
        this.$http.post(getOplogApiList,params).then((res) => {
          const data = res.result.list
          this.tableData = data
          this.tablePage.total = res.result.total
          this.tablePage.currentPage = res.result.pageNum
          this.tablePage.pageNum = res.result.pageNum
          this.tablePage.pageSize = res.result.pageSize
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      }, 20)
    },
    clearAll () {
      this.queryParam = {}
      this.findList()
    },
    openParamInfo (value) {
      if (value) {
        this.reqParams = JSON.parse(value)// JSON.stringify(value, null, 4)
        this.visible = true
      } else {
        modal.info({ title: '提示', content: '参数为空' })
      }
    },
    onHistroyChange (e) {
      this.isHistoryChecked = e.target.checked
    }
  },
  watch: {
    /*
      'selectedRows': function (selectedRows) {
        this.needTotalList = this.needTotalList.map(item => {
          return {
            ...item,
            total: selectedRows.reduce( (sum, val) => {
              return sum + val[item.dataIndex]
            }, 0)
          }
        })
      }
      */
  }
}
</script>
